<?php

namespace app\admin\controller\housekeep\houses;

use app\common\controller\AdminController;

use think\Controller;
use think\Request;
use PHPExcel;
use think\Db;
use think\facade\Cache;

/**
 * 导入历史
 */
class ImportMsg extends AdminController
{

    /**
     * ImportRecord模型对象
     */
    protected $model = null;

    public function __construct() {
            parent::__construct();
            $this->model = model('ImportRecord');

        }

    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->get('type') == 'ajax') {
            $page = $this->request->get('page', 1);
            $limit = $this->request->get('limit', 10);
            $search = (array)$this->request->get('search', []);
            return json($this->model->getImportRecordList($page, $limit, $search));
        }
        $basic_data = [
            'title' => '导入历史',
            'data'  => '',
        ];
        return $this->fetch('', $basic_data);
    }

    /**
     * 添加
     * @return mixed
     */
    public function add() {
        if (!$this->request->isPost()) {
            $basic_data = [
                'title' => '添加导入历史',
            ];
            return $this->fetch('add', $basic_data);
        } else {
            $post = $this->request->post();

            //验证数据
            $validate = $this->validate($post, 'app\admin\validate\ImportRecord.add');
            if (true !== $validate) return __error($validate);

            //保存数据,返回结果
            return $this->model->addData($post);
        }
    }

    /**
     * 修改
     * @return mixed|string|\think\response\Json
     */
    public function edit() {
        if (!$this->request->isPost()) {

            //查找所需修改的导入历史
            $data = $this->model->where('id', $this->request->get('id'))->find();
            if (empty($data)) return msg_error('暂无数据，请重新刷新页面！');

            //基础数据
            $basic_data = [
                'title'    => '修改导入历史',
                'info' => $data,
            ];
            return $this->fetch('edit', $basic_data);
        } else {
            $post = $this->request->post();

            //验证数据
            $validate = $this->validate($post, 'app\admin\validate\ImportRecord.edit');
            if (true !== $validate) return __error($validate);

            //保存数据,返回结果
            return $this->model->editData($post);
        }
    }

    /**
     * 删除
     * @return \think\response\Json
     */
    public function del() {
        $get = $this->request->get();

        //验证数据
        if (!is_array($get['id'])) {
            $validate = $this->validate($get, 'app\admin\validate\ImportRecord.del');
            if (true !== $validate) return __error($validate);
        }

        //执行删除操作
        return $this->model->delData($get['id']);
    }

    /**
     * 更改状态
     * @return \think\response\Json
     */
    public function status() {
        $get = $this->request->get();

        //验证数据
        $validate = $this->validate($get, 'app\admin\validate\ImportRecord.status');
        if (true !== $validate) return __error($validate);

        //判断状态
        $status = $this->model->where('id', $get['id'])->value('status');
        $status == 1 ? list($msg, $status) = ['启用成功', $status = 0] : list($msg, $status) = ['禁用成功', $status = 1];

        //执行更新操作操作
        $update = $this->model->where('id', $get['id'])->update(['status' => $status]);

        if ($update >= 1) return __success($msg);
        return __error('数据有误，请刷新重试！');
    }

    // 导入
    public function importFile() {

        //接收前台文件
        $ex = $_FILES['file'];
        $path = './excel';//设置移动路径
        move_uploaded_file($ex['tmp_name'],$path);
        // 实例化类库
        $obj_phpexcel = new \PHPExcel();
        if (explode('.',$ex['name'])[1] =='xls') {
            $objReader = \PHPExcel_IOFactory::createReader('Excel5');
            $objData = $objReader->load($path, $encode = 'utf-8');
        } else {
            // todo 兼容xlsx
            return __error('请上传xls格式');
        }
        $excel_array=$objData->getsheet(0)->toArray();
        // 数据键值
        $dataKeys = $excel_array[2];
        unset($excel_array[0]);
        unset($excel_array[1]);
        unset($excel_array[2]);

        // 处理数据
        foreach($excel_array as $k => $v) {
            foreach ($v as $k1 => $v1) {
                $excel_array[$k][$dataKeys[$k1]] = $v1;
                unset($excel_array[$k][$k1]);
            }
        }



        // 表结构
        $tableColumns = Db::name('import_msg')->query('show columns from import_msg');
        $tableColumns = array_column($tableColumns, 'Field');

        // 错误信息
        $errmsg = '';
        // 总数
        $allNum = count($excel_array);
        // 失败
        $errNum = 0;


        // 初始化错误格式
        $errArr = [
            'bd_num' => 0, // 楼栋号
            'unit_num' => 0, // 单元号
            'houses_num' => "1", // 房号
            'houses_type' => '0', // 房产类型
            'houses_area' => 0, // 建筑面积
            'houses_admin' => '', // 房管员
            'pro_type' => '', // 房屋类型
            'name' => "暂无", // 业主姓名
            'user_unit' => '', // 身份证号
            'checktime' => date('Y/m/d'), // 入住日期
            'phone' => 0, // 手机号
            'spare_phone' => 0, // 备用手机号
            'work' => '', // 工作单位
            'car_unit' => '', // 车牌号
            'car_unit_other' => '', // 车牌号2
            'remarks' => '', // 备注
            'err_msg' => '', // 错误原因

        ];

        $recordData = [
            'name' => $ex['name'],
            'createtime' => date('Y/m/d h-m-s'),
            'user' => 1,
            'err_msg' => ''.$errNum.'/'.$allNum.'',
            'status' => 1,
            'is_deleted' => 0
        ];
        $recordId = Db::name('import_record')->insertGetId($recordData);

        // 组装住户信息
        foreach($excel_array as $k => $v) {
            $insertData = [];
            foreach ($v as $k1=>$v1) {
                switch ($k1) {
                    case $k1 == '楼号':
                        $isHasBd = model('BdMessage')->where([['unit', '=', $v1], ['is_deleted', '=', 0], ['status', '=', '1']])->find();
                        if(empty($isHasBd)) {
                            model('BdMessage')->insert([
                               'unit' => $v1,
                               'cm_message_id' => session('cmId', '', 'think'),
                               'name' => $v1.'栋',
                               'status' => 1,
                               'is_deleted' => 0,
                               'period_message_id' => 2
                            ]);
                            $insertData['bd_num'] = $v1;
                            $insertData['cm_num'] = session('cmId', '', 'think');
                        } else {
                            $insertData['bd_num'] = $v1;
                            $insertData['cm_num'] = session('cmId', '', 'think');
                        }
                        break;
                    case $k1 == '区期':
                        $insertData['period_num'] = 2;
                        break;
                    case $k1 == '户号':
                        $insertData['houses_num'] = trim($v1);
                        break;
                    case $k1 == '单元':
                        $bdId = model('BdMessage')->where([['unit', '=',$insertData['bd_num']], ['cm_message_id', '=', $insertData['cm_num'], ['period_message_id', '=', $insertData['period_num']]]])->find();
                        $isHasUnit = model('UnitMessage')->where([['info', '=', $v1], ['is_deleted', '=', 0], ['status', '=', 0], ['cm_message_id', '=', $insertData['cm_num']], ['bd_message_id', '=', $bdId['id']], ['period_message_id', '=', $insertData['period_num']]])->find();
                        if(empty($isHasUnit)) {
                            model('UnitMessage')->insert([
                                'info' => $v1,
                                'cm_message_id' => session('cmId', '', 'think'),
                                'unit' => $bdId['unit'].'-'.$v1,
                                'bd_message_id' => $bdId['id'],
                                'period_message_id' => 2,
                                'is_deleted' => 0,
                                'status' => 0
                            ]);
                            $insertData['unit_num'] = $v1;
                        } else {
                            $insertData['unit_num'] = $v1;
                        }
                        break;
                    case $k1 == '姓名':
                        $insertData['name'] = $v1;
                        break;
                    case \strstr($k1, '类型'):
                        $insertData['type'] = $v1 == '高层住宅' ? 2 : 1;
                        break;
                    case $k1 == '房屋标签':
                        $labelsid = model('Labels')->where('name', 'LIKE', "%{$v1}%")->column('id');
                        $insertData['labels_id'] = isset($labelsid) ? implode(',', $labelsid) : "";
                        break;
                    case $k1 == '手机号':
                        $insertData['phone'] = $v1;
                        if($v1 == NULL) $errmsg = '手机号不能为空';
                        break;
                    case $k1 == '身份证号':
                        $insertData['user_unit'] = $v1;
                        break;
                    case $k1 == '面积':
                        $insertData['houses_area'] = $v1;
                        break;
                    case $k1 == '公摊系数':
                        $insertData['public_num'] = $v1;
                        break;
                    case $k1 == '系数面积':
                        $insertData['num_area'] = $v1;
                        break;
                    case strstr($k1, '类型'):
                        $insertData['type'] = $v1 == '高层住宅' ? 2 : 1;
                        break;
                    case $k1 == '入住日期':
                        $insertData['in_time'] = $v1;
                        break;
                    case $k1 == '入住信息':
                        $insertData['in_message'] = $v1;
                        break;
                    case $k1 == '交费时间':
                        $insertData['pay_time'] = $v1 || '0000-00-00';
                        break;
                    case $k1 == '备注':
                        $insertData['remarks'] = $v1 || "";
                        break;
                }
            }
            $houseData = [
                'cm_message_id' => session('cmId', '', 'think'),
                'period_message_id' => model('period_message')->where('unit', $insertData['period_num'])->value('id'),
                'bd_message_id' => model('bd_message')->where('unit', $insertData['bd_num'])->value('id'),
                'unit_message_id' => model('unit_message')->where([['unit', 'LIKE', '%'.$insertData['bd_num'].'-'.$insertData['unit_num'].'%']])->value('id'),
                'area' => $insertData['houses_area'],
                'type' => $insertData['type'],
                'labels_id' => $insertData['labels_id'],
                'num_area' => $insertData['num_area'],
                'public_price' => $insertData['public_num'],
                'in_time' => $insertData['in_time'],
                'name' => $insertData['houses_num']
            ];


            // 验证添加
            if($insertData['user_unit']) {
                $isData = Db::name('import_msg')->where([['user_unit', '=',$insertData['user_unit']], ['is_deleted', '=', 0]])->find();
            }
            if(empty($isData) && $errmsg == "") {
                $houseId = Db::name('houses')->insertGetId($houseData);
                // 组装业主信息
                $houseUserInfo = [
                    'name' => $insertData['name'] ? $insertData['name'] : '',
                    'phone' => $insertData['phone'],
                    'cm_message_id' => session('cmId', '', 'think'),
                    'unit_message_id' => model('unit_message')->where([['unit', 'LIKE', '%'.$insertData['bd_num'].'-'.$insertData['unit_num'].'%']])->value('id'),
                    'bd_message_id' => model('bd_message')->where('unit', $insertData['bd_num'])->value('id'),
                    'houses_id' => $houseId
                ];
                $insertData['import_record_id'] = $recordId;
                Db::name('houses_info')->insert($houseUserInfo);
                Db::name('import_msg')->insert($insertData);
            } else {
                if(!empty($isData)) $errmsg = '数据重复';
                foreach ($insertData as $k => $v) {
                    if(in_array($k, array_keys($errArr))) {
                        $errArr[$k] = $v;
                    }
                    $errArr['err_msg'] = $errmsg;
                    $errArr['import_record_id'] = $recordId;
                }
                Db::name('import_err')->strict(false)->insert($errArr);
                $errNum++;
                $errmsg = "";
            }
        }

        return __success('已完成');
    }


    /**
     * 导入历史导出
     */
    public function index_exp()
    {
        if ($this->request->get('type') == 'export') {
            $page = $this->request->get('page', 1);
            $flag = $this->request->get('flag');
            $limit = $this->def_exp;
            $id = $this->request->get('id');
            $allData = $this->exportHouses($page, $limit, $id);
            $data = $allData['data'];
            if($page == 1){
                if($allData['count'] > 0){
                    Cache::set('exp_info_xls_'.$flag,['count'=>$allData['count'],'data'=>[]],60);
                }else{
                    return __error('没有符合条件的数据!');
                }
            }
            if($data){
                $cacheinfo=Cache::get('exp_info_xls_'.$flag);
                $allpage=ceil( $cacheinfo['count'] / $limit );
                $newlist=array_merge($cacheinfo['data'],$data);
                Cache::set('exp_info_xls_'.$flag,['count'=>$cacheinfo['count'],'data'=>$newlist],60);
                return json(['code'=>0,'msg'=>'正在下载……进度为（'.$page.'/'.$allpage.'）','allpage'=>$allpage,'page'=>$page+1]);
            }else{
                $xlsName = "住户信息";
                $xlsCell = [
                    ['id', '编号'],
                    ['bd_num', '楼号'],
                    ['unit_num', '单元'],
                    ['houses_num', '户号'],
                    ['name', '姓名'],
                    ['phone', '手机号'],
                    ['user_unit', '身份证'],
                    ['houses_area', '面积'],
                    ['public_num', '公摊系数'],
                    ['labels_id', '房屋标签'],
                    ['num_area', '系数面积'],
                    ['in_time', '入住日期'],
                ];
                $cacheinfo=Cache::get('exp_info_xls_'.$flag);
                $url = exportExcel($xlsName, $xlsCell, $cacheinfo['data'],true);
                return json(['code'=>2,'url'=>$url]);
            }
        }
    }


    /**
     * 导入错误导出
     */
    public function index_err_exp()
    {
        if ($this->request->get('type') == 'export') {
            $page = $this->request->get('page', 1);
            $flag = $this->request->get('flag');
            $limit = $this->def_exp;
            $errId = $this->request->get('id');
            $allData = model('ImportErr')->exportList($page, $limit, $errId);
            $data = $allData['data'];
            if($page == 1){
                if($allData['count'] > 0){
                    Cache::set('exp_info_xls_err'.$flag,['count'=>$allData['count'],'data'=>[]],60);
                }else{
                    return __error('没有符合条件的数据!');
                }
            }
            if($data){
                $cacheinfo=Cache::get('exp_info_xls_err'.$flag);
                $allpage=ceil( $cacheinfo['count'] / $limit );
                $newlist=array_merge($cacheinfo['data'],$data);
                Cache::set('exp_info_xls_err'.$flag,['count'=>$cacheinfo['count'],'data'=>$newlist],60);
                return json(['code'=>0,'msg'=>'正在下载……进度为（'.$page.'/'.$allpage.'）','allpage'=>$allpage,'page'=>$page+1]);
            }else{
                $xlsName = "住户信息";
                $xlsCell = [
                    ['id', '编号'],
                    ['bd_num', '楼号'],
                    ['unit_num', '单元'],
                    ['houses_num', '户号'],
                    ['name', '姓名'],
                    ['phone', '手机号'],
                    ['user_unit', '身份证'],
                    ['houses_area', '面积'],
                    ['pro_type', '房屋类型'],
                    ['checktime', '入住日期'],
                    ['remarks', '备注'],
                    ['err_msg', '错误原因'],
                    ['is_deleted', '是否删除']
                ];
                $cacheinfo=Cache::get('exp_info_xls_err'.$flag);
                $url = exportExcel($xlsName, $xlsCell, $cacheinfo['data'],true);
                return json(['code'=>2,'url'=>$url]);
            }
        }
    }

    // 测试
    public function exportHouses($page = 1, $limit = 10, $id) {

        $where = [['is_deleted', '=', 0], ['import_record_id', '=', $id]];

        $count = Db::name('import_msg')->where($where)->count();
        $data = Db::name('import_msg')->where($where)->page($page, $limit)->order(['id' => 'desc'])->select();
        empty($data) ? $msg = '暂无数据！' : $msg = '查询成功！';
        $info = [
            'limit'        => $limit,
            'page_current' => $page,
            'page_sum'     => ceil($count / $limit),
        ];
        $list = [
            'code'  => 0,
            'msg'   => $msg,
            'count' => $count,
            'info'  => $info,
            'data'  => $data,
        ];
        return $list;
    }

}
